package com.suyin.ximoon.controller.system;


import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suyin.ximoon.annotation.SystemLog;
import com.suyin.ximoon.controller.base.BaseController;
import com.suyin.ximoon.exception.ServiceException;
import com.suyin.ximoon.exception.SystemException;
import com.suyin.ximoon.model.LyUser;
import com.suyin.ximoon.model.LyUserRole;
import com.suyin.ximoon.model.bo.Page;
import com.suyin.ximoon.plugin.mybatis.Criteria;
import com.suyin.ximoon.plugin.mybatis.Restriction;
import com.suyin.ximoon.service.LyResUserService;
import com.suyin.ximoon.service.LyUserRoleService;
import com.suyin.ximoon.service.LyUserService;
import com.suyin.ximoon.util.Common;
import com.suyin.ximoon.util.JsonUtils;
import com.suyin.ximoon.util.POIUtils;
import com.suyin.ximoon.util.PasswordHelper;
import com.suyin.ximoon.util.Tools;

/**
 * 
 * @author lanyuan 2014-11-19
 * @Email: mmm333zzz520@163.com
 * @version 3.0v
 */
@Controller
@RequestMapping("/user/")
public class UserController extends BaseController {
	@Resource
	private LyUserService lyuserService;
	@Resource
	private  LyUserRoleService lyUserRoleService;
	@Resource
	private  LyResUserService lyResUserService;
	@RequestMapping("list")
	public String listUI(Model model) throws Exception {
		model.addAttribute("res", findByRes());
		return Common.BACKGROUND_PATH + "/system/user/list";
	}

	@ResponseBody
	@RequestMapping("findByPage")
	public Page findByPage( String pageNow,String pageSize,String accountName) throws Exception {
		 Page page = new Page();
         if (Tools.notEmpty( pageNow))
         {
             page.setCurrentPage(Integer.parseInt(pageNow));
         }
         if (Tools.notEmpty(pageSize))
         {
             page.setShowCount(Integer.parseInt(pageSize));
         }
         else
         {
             page.setShowCount(20);
         }
         LyUser lyuser = new LyUser();
         if (Tools.notEmpty(accountName))
         {
        	 lyuser.setAccountName(accountName);
         }
         lyuser.setPage(page);
         page.setRecords(lyuserService.queryUserByPage(lyuser));//不调用默认分页,调用自已的mapper中findUserPage
        return page;
	}
	
	@RequestMapping("/export")
	public void download(HttpServletRequest request, HttpServletResponse response,String exportData) throws IOException, ServiceException {
		String fileName = "用户列表";
		List<Map<String, Object>> listMap = JsonUtils.parseJSONList(exportData);
		LyUser lyuser = new LyUser();
		List<LyUser> lis = lyuserService.queryAll(lyuser);
		JsonUtils.toList(JsonUtils.listToJson(lis));
		POIUtils.exportToExcel(response, listMap,JsonUtils.toList(JsonUtils.listToJson(lis)), fileName);
	}

	@RequestMapping("addUI")
	public String addUI(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/add";
	}

	@ResponseBody
	@RequestMapping("addEntity")
	@SystemLog(module="系统管理",methods="用户管理-新增用户")//凡需要处理业务逻辑的.都需要记录操作日志
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	public String addEntity(LyUser userFormMap,String txtGroupsSelect){
		try {
			 
			userFormMap.setPassword("123456789");
			PasswordHelper passwordHelper = new PasswordHelper();
			passwordHelper.encryptPassword(userFormMap);
			lyuserService.insert(userFormMap);//新增后返回新增信息
			if (!Common.isEmpty(txtGroupsSelect)) {
				String[] txt = txtGroupsSelect.split(",");
				LyUserRole userGroupsFormMap = new LyUserRole();
				for (String roleId : txt) {
					userGroupsFormMap.setRoleId(Integer.valueOf(roleId));
					userGroupsFormMap.setUserId(userFormMap.getId());
					lyUserRoleService.insert(userGroupsFormMap);
				}
			}
		} catch (Exception e) {
			 throw new SystemException("添加账号异常");
		}
		return "success";
	}

	@ResponseBody
	@RequestMapping("deleteEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="用户管理-删除用户")//凡需要处理业务逻辑的.都需要记录操作日志
	public String deleteEntity() throws Exception {
		String[] ids = getParaValues("ids");
		Criteria c = new Criteria();
		for (String id : ids) {
			c .add(Restriction.eq("userId", id));
			lyUserRoleService.delete(c);
			lyResUserService.delete(c);
			 c = new Criteria();
			 c .add(Restriction.eq("id", id));
			lyuserService.delete(c);
		}
		return "success";
	}

	@RequestMapping("editUI")
	public String editUI(Model model) throws Exception {
		String id = getPara("id");
		if(Common.isNotEmpty(id)){
			Criteria c = new Criteria();
			c .add(Restriction.eq("id", id));
			model.addAttribute("user", lyuserService.queryOne(c));
		}
		return Common.BACKGROUND_PATH + "/system/user/edit";
	}

	@ResponseBody
	@RequestMapping("editEntity")
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="用户管理-修改用户")//凡需要处理业务逻辑的.都需要记录操作日志
	public String editEntity(LyUser userFormMap,String txtGroupsSelect) throws Exception {
		lyuserService.update(userFormMap);
		Criteria c = new Criteria();
		c .add(Restriction.eq("userId", userFormMap.getId()));
		lyUserRoleService.delete(c);
		if(!Common.isEmpty(txtGroupsSelect)){
			String[] txt = txtGroupsSelect.split(",");
			LyUserRole userGroupsFormMap = new LyUserRole();
			for (String roleId : txt) {
				userGroupsFormMap.setRoleId(Integer.valueOf(roleId));
				userGroupsFormMap.setUserId(userFormMap.getId());
				lyUserRoleService.insert(userGroupsFormMap);
			}
		}
		return "success";
	}
	/**
	 * 验证账号是否存在
	 * 
	 * @author lanyuan Email：mmm333zzz520@163.com date：2014-2-19
	 * @param name
	 * @return
	 * @throws ServiceException 
	 */
	@RequestMapping("isExist")
	@ResponseBody
	public boolean isExist(String name) throws ServiceException {
		Criteria c = new Criteria();
		c .add(Restriction.eq("accountName", name));
		LyUser lyuser= lyuserService.queryOne(c);
		if (lyuser == null) {
			return true;
		} else {
			return false;
		}
	}
	
	//密码修改
	@RequestMapping("updatePassword")
	public String updatePassword(Model model) throws Exception {
		return Common.BACKGROUND_PATH + "/system/user/updatePassword";
	}
	
	//保存新密码
	@RequestMapping("editPassword")
	@ResponseBody
	@Transactional(readOnly=false)//需要事务操作必须加入此注解
	@SystemLog(module="系统管理",methods="用户管理-修改密码")//凡需要处理业务逻辑的.都需要记录操作日志
	public String editPassword(LyUser userFormMap,String newpassword ) throws Exception{
		 
		//这里对修改的密码进行加密	
		userFormMap.setPassword(newpassword);
		PasswordHelper passwordHelper = new PasswordHelper();
		passwordHelper.encryptPassword(userFormMap);
		lyuserService.update(userFormMap);
		return "success";
	}
}